#include "../include/Shared_Pointer.hpp"
#include "apue.h"

void* ThreadFunc1(void* arg);
void* ThreadFunc2(void* arg);

int main(void)
{
    foo<int>* fp = foo_alloc<int>(1);
    *fp->t_value = 0;
    int err;    //记录线程错误信息
    pthread_t tid_1,tid_2;      //线程id
    void* rval;     //返回值

    err = pthread_create(&tid_1,NULL,ThreadFunc1,fp);
    if(err != 0)
    {
        err_exit(err,"Can't Create Thread Function 1");
    }
    err = pthread_create(&tid_2,NULL,ThreadFunc2,fp);
    if(err != 0)
    {
        err_exit(err,"Can't Create Thread Function 2");
    }

    err = pthread_join(tid_1,&rval);
    if(err != 0)
    {
        err_exit(err,"Join Thread 1 error");
    }
    err = pthread_join(tid_2,&rval);
    if(err != 0)
    {
        err_exit(err,"Join Thread 2 error");
    }
    printf("In Main Thread The Struct foo Have Count %d\n",fp->t_count);
    foo_rele(fp);
    return 0;
}

void* ThreadFunc1(void* arg)
{
    printf("This is Thread Function 1\n");
    foo<int>* fp = (foo<int>*)arg;
    foo_hold(fp);
    for(int i=0;i<5;++i)
    {
        pthread_mutex_lock(&fp->t_lock);
        (*fp->t_value)++;
        pthread_mutex_unlock(&fp->t_lock);
    }
    foo_rele(fp);
    return (void*)0;
}

void* ThreadFunc2(void* arg)
{
    printf("This is Thread Function 2\n");
    foo<int>* fp = (foo<int>*)arg;
    foo_hold(fp);
    for(int i=0;i<5;++i)
    {
        pthread_mutex_lock(&fp->t_lock);
        printf("We Can Get foo value %d in Thread Function 2\n",*fp->t_value);
        pthread_mutex_unlock(&fp->t_lock);
        sleep(1);
    }
    foo_rele(fp);
    return (void*)0;
}
